#include "config.h"
#include "encoding_manager.h"
#include <string.h>
#include<stdio.h>
static int isUtf8Coding(unsigned char *pucBufHead);
static int Utf8GetCodeFrmBuf(unsigned char *pucBufStart, unsigned char *pucBufEnd, unsigned int *pdwCode);
static T_EncodingOpr g_tUtf8EncodingOpr = {
    .name = "utf-8",
    .iHeadLen = 3,
    .isSupport = isUtf8Coding,
    .GetCodeFrmBuf = Utf8GetCodeFrmBuf,
};
int isUtf8Coding(unsigned char *pucBufHead)
{
    const char aStrUtf8[] = {0xEF, 0xBB, 0xBF, 0};
    // const char aStrUtf16le[] = {0xFF, 0xFE, 0};
    // const char aStrUtf16be[] = {0xFE, 0xFF, 0};
    if (strncmp((const char*)pucBufHead, aStrUtf8, 3) == 0)
    {
        return 0;
    }
    else
    {
        return -1;
    }
}
int GetPreOneBits(unsigned char c)
{
    int i;
    int j = 0;

    for (i = 7; i >= 0; i--)
    {
        if (!(c & (1 << i)))
            break;
        else
            j++;
    }
    return j;
}
int Utf8GetCodeFrmBuf(unsigned char *pucBufStart, unsigned char *pucBufEnd, unsigned int *pdwCode)
{
    if (pucBufStart >= pucBufEnd)
    {
       
        return 0;
    }
    int dwSum = 0;
    int iNum = GetPreOneBits(pucBufStart[0]);
    // printf("iNum is : %d\n",iNum);
    if (pucBufStart + iNum >= pucBufEnd)
    {
      
        return 0;
    }
    unsigned char ucVal = *pucBufStart;
    if (iNum == 0)
    {

        *pdwCode = pucBufStart[0];
        return 1;
    }
    else
    {
        ucVal = ucVal << iNum;
        ucVal = ucVal >> iNum;
        dwSum += ucVal;
        for (int i = 1; i < iNum; i++)
        {
            ucVal = pucBufStart[i] & 0x3f;
            dwSum = dwSum << 6;
            dwSum += ucVal;
        }
        *pdwCode = dwSum;
        return iNum;
    }
}
int Utf8EncodingInit(void)
{
    AddFontOprForEncoding(&g_tUtf8EncodingOpr, GetFontOpr("freetype"));
    AddFontOprForEncoding(&g_tUtf8EncodingOpr, GetFontOpr("ascii"));

    return RegisterEncodingOpr(&g_tUtf8EncodingOpr);
}